package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.core.io.ClassPathResource;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class LocalJSONFileUtil {
    public static Object getJSONByKey(String filepath, String key) throws IOException {
        String text = LocalJSONFileUtil.getFileText(filepath);
        JSONObject object = new JSONObject();
        if ((StringUtils.isNoneBlank(text))){
            object = parseObjest(text);
        }
        return object.get(key);
    }

    public static JSONObject parseObjest(String text){
        return JSONObject.parse(text);
    }

    public static String getFileText(String filepath) throws IOException {
        StringBuffer sb = new StringBuffer();
        try {
            ClassPathResource classPathResource = new ClassPathResource(filepath);
            Reader reader = new InputStreamReader(classPathResource.getInputStream());
            int ch = 0;
            while ((ch = reader.read())!= -1){
                sb.append((char)ch);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString().replace("\r\n","");
    }
}
